<template>
  <el-dialog v-model="showAddDialog" title="新建申请" width="30%" :show-close="false"
    :close-on-press-escape="false" :close-on-click-modal="false">
    <el-form :model="appObject.form" label-width="120px" style="margin-top: 20px;" ref="formRef" :rules="rules">
      <el-form-item label="申请理由" prop="description">
        <el-input type="textarea" v-model="appObject.form.description" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose()">取消</el-button>
        <el-button type="primary" @click="submitForm(formRef)">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
  import { ref, reactive, defineProps } from 'vue'
  import applyStore from '../store/apply.js'
  import userStore from '../store/user.js'
  import {storeToRefs} from 'pinia'
  import { createApply } from '../http/applyApi.js'
  import { ElNotification } from 'element-plus'
  
  // 父组件传递过来方法，便于子组件调用刷新页面
    const props = defineProps({
      callbackFunc: Function,
      currentWgId: Number
    })
  
  const aStore = applyStore()
  const { showAddDialog } = storeToRefs(aStore)
  
  const uStore = userStore()
  const { user, getUserId } = storeToRefs(uStore)
  
  
  const appObject = reactive({
    form: {
      wgId: props.currentWgId,
      userId: uStore.getUserId,
      description: '',
      status: 0
    }
  })
  
  // 初始化页面数据
  const initData = () => {
    appObject.form = {
      wgId: props.currentWgId,
      userId: uStore.getUserId,
      description: '',
      status: 0
    }
  }
  
  // 表单校验
  const rules = reactive({
    description: [{
      required: true,
      message: '请输入申请理由',
      trigger: 'blur'
    }, ]
  })
  
  const formRef = ref()
  
  const submitForm = (formEL) => {
    if (!formEL) return
    formEL.validate((valid) => {
      if (valid) {
       createApply(appObject.form).then(res =>{
         res = res.data
         ElNotification({
           title: '申请成功',
           message: res.msg,
           type: 'success',
         })
         initData()
         props.callbackFunc()
         aStore.updateShowAddDialog(false)
       })
       
      }else{
        return false
      }
    })
  }
  
  // 关闭对话框执行的方法
  const handleClose = () => {
    initData()
    aStore.updateShowAddDialog(false)
  }
</script>

<style scoped>
</style>